import { useRef } from 'react';
import { useParams } from 'react-router-dom';

import { Button } from 'antd';
import Layout from '@/components/layout/Layout';
import Slide from '@/pages/detail/components/Slide';
import ProductInfo from '@/pages/detail/components/ProductInfo';
import ProductPackage from '@/pages/detail/components/ProductPackage';
import Order from '@/pages/detail/components/Order';
import UserNotice from '@/pages/detail/components/UserNotice';
import Contact from '@/pages/detail/components/Contact';
import Cookie from 'js-cookie'
import icon_top from '@/assets/images/icons/top.svg';

const Wrap = css.div`
  padding: 12px;
  .buy-now{
    height: 68px;
    padding: 12px;
    background: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    ${_gb.flex()};
    display: none;
    &.active{
      display: flex;
    }
    .go-top{
      ${_gb.flex()};
      margin-right: 12px;
    }
    a{
      display: block;
      flex: 1;
    }
  }
`;

const DetailPage = () => {
  const [buyVisible, setBuyVisible] = useState(false);
  const params = useParams();
  const goodsId = params?.id;
  const timerStart = useRef(+new Date());
  const isLog = useRef(false);
  const { data: goodsInfo } = useSwr(goodsId ? [_api.detail_desc, goodsId, 'p1'] : null, (url, id) =>
    _ajax.get(url, { params: { compose_sn: id } }),
  );
  const { data: goodsComposes } = useSwr(goodsId ? [_api.detail_product, goodsId, 'p2'] : null, (url, id) =>
    _ajax.get(url, { params: { compose_sn: id } }),
  );

  useEffect(() => {
    const pixelId = goodsInfo?.data?.pixel;
    pixelId && Cookie.set('pixel', pixelId)
    if (pixelId && window?.fbq) {
      window.fbq('init', pixelId, {
        fbc: Cookie.get('_fbc'),
        pbp: Cookie.get('_fbp')
      });
      console.log('pageView');
      setTimeout(() => {
        window.fbq('track', 'PageView');
        sendEvent({
          event: 'page_view'
        })
      }, 0);
    }
  }, [goodsInfo]);

  useEffect(() => {
    window.document.addEventListener('scroll', (e) => {
      const y = window.scrollY;
      const skuVisibility = document.getElementById('sku');
      if (!isLog.current && isElementInViewport(skuVisibility)) {
        try {
          window.fbq('track', 'AddToCart');
          sendEvent({
            event: 'add_to_cart'
          })
          isLog.current = true;
        } catch (error) {
          console.log(error);
        }
      }
      setBuyVisible(y > 300 && y < window.document.body.scrollHeight - 1167);
    });
  }, []);

  const isElementInViewport = (el) => {
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  };
  useEffect(() => {
    sendLog({
      compose_sn: goodsId,
      op: 'request',
    });
    setTimeout(() => {
      sendLog({
        op: {
          browse: {
            second: 10,
          },
        },
      });
      window.fbq('track', 'PageView');
      sendEvent({
        event: 'page_view'
      })
    }, 10000);
    setTimeout(() => {
      sendLog({
        op: {
          browse: {
            second: 60,
          },
        },
      });
    }, 60000);
  }, []);
  const sendLog = async ({ compose_sn = goodsId, op = {} }) => {
    try {
      const data = {
        pre_url: document.referrer || window.location.origin,
        url: window.location.href,
        compose_sn,
        op,
      };
      await _ajax.post(_api.log, data);
    } catch (error) {
      console.log(error);
    }
  };

  const handleGoTop = () => {
    window.scrollTo(0, 0);
  };

  /*
   * @Desc: 事件发送
   * @params: {String}
   * @return: {Object}
  */
  const sendEvent = (params = {}) => {
      const pixel = Cookie.get('pixel')
      if(!pixel) return;
      _ajax.post(_api.postEvent, {
        ...params,
        pixel,
        fbc: Cookie.get('_fbc'),
        pbp: Cookie.get('_fbp'),
        src_url: location.href
      })
  };

  return (
    <Layout>
      <Wrap>
        <Slide data={goodsInfo?.data?.main_carousel} />
        <ProductInfo data={goodsInfo?.data} />
        <ProductPackage />
        <Order goodsId={goodsId} sendLog={sendLog} composes={goodsComposes?.data?.composes} />
        <UserNotice />
        <Contact line={goodsInfo?.data?.line_url} fb={goodsInfo?.data?.fb_url} />
        <div className={classnames('buy-now', { active: buyVisible })}>
          <div onClick={handleGoTop} className="go-top">
            <Icon component={icon_top} />
          </div>
          <a onClick={() => setBuyVisible(false)} href="#buy">
            <Button type="primary" block>
              立即購買
            </Button>
          </a>
        </div>
      </Wrap>
    </Layout>
  );
};

export default DetailPage;
